package com.nari.kmd_dataservice.controller;

import com.nari.kmd_dataservice.constant.GlobalVariable;
import com.nari.kmd_dataservice.mapper.ServerMapper;
import com.nari.kmd_dataservice.pojo.dto.cancellEvent.CancellEventDto;
import com.nari.kmd_dataservice.pojo.dto.common.CommonResponseDTO;
import com.nari.kmd_dataservice.pojo.dto.targetResponse.TargerResponseDto;
import com.nari.kmd_dataservice.pojo.dto.targetVerify.TargerVerifyDto;
import com.nari.kmd_dataservice.pojo.entity.LaUser;
import com.nari.kmd_dataservice.pojo.entity.ResponseEventRange;
import com.nari.kmd_dataservice.pojo.request.cancellEvent.CancellEventRequest;
import com.nari.kmd_dataservice.pojo.request.targetResponse.TargerResponseRequest;
import com.nari.kmd_dataservice.pojo.request.targetVerify.TargerVerifyRequest;
import com.nari.kmd_dataservice.service.AutoServerService;
import com.nari.kmd_dataservice.service.LoadPlatformService;
import com.nari.kmd_dataservice.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.*;

/**
 * @ClassName: LoadPlatformController
 * @Description:
 * @Author: zhangnaijiang
 * @Date: 2022/01/22 14:53
 * @Version 1.0.0
 */
@RestController
@RequestMapping(value = "/server")
@Api(value = "负荷聚合平台", tags = "负荷聚合平台")
@Slf4j
public class LoadPlatformController {
    @Autowired
    private RestTemplate restTemplate;
    @Resource
    private ServerMapper serverMapper;
    @Resource
    private LoadPlatformService loadPlatformService;
    @Resource
    private AutoServerService autoServerService;

    @PostMapping(value = "/test")
    @ApiOperation(value = "请求负荷聚合平台测试", notes = "用于明文请求负荷聚合平台测试，完整参数测试接口，{}参数测试自动业务")
    public String laRegister(@RequestHeader Map<String,String> headers, @RequestBody String jsonParameter) throws Exception {
        String requestURI = headers.get("requesturi");
        log.info("测试负荷聚合平台URI：{}，参数：{}", requestURI, jsonParameter);
        if(requestURI==null){
            return GsonUtils.toJsonWtihNullField(new CommonResponseDTO("02", "无method"));
        }
        LaUser laUser = null;
        if(jsonParameter.length()<5){//不传参，自动生成，模拟自动请求
            log.debug("测试负荷聚合平台URI：{}，不传参，自动生成，模拟自动请求", requestURI);
            laUser = GlobalVariable.laUserList.get(0);
            if(requestURI.equals("targetVerify")){//电力需求响应系统认证验证
                jsonParameter = GsonUtils.toJsonWtihNullField(laUser);
            }
            else if(requestURI.equals("targetResponse")){//电力需求响应系统发布需求响应事件
                return autoServerService.autoTargetResponse();
            }
            else if(requestURI.equals("cancellEvent")){
                ResponseEventRange responseEventRange = serverMapper.getOnePublishResponseEventRangeByLaID(laUser.getLaRegistRationId());
                if(responseEventRange==null){
                    return GsonUtils.toJsonWtihNullField(new CommonResponseDTO("02", laUser.getUserName()+"-"+laUser.getRegistRationId()+"自动请求无发布成功事件"));
                }
                CancellEventRequest cancellEventRequest = new CancellEventRequest();
                cancellEventRequest.setRegistRationId(laUser.getRegistRationId());
                cancellEventRequest.setEventId(responseEventRange.getEventId());
                cancellEventRequest.setProcessStatus(2);
                jsonParameter = GsonUtils.toJsonWtihNullField(cancellEventRequest);
            }
        }
        else{
            JSONObject jsonObject = new JSONObject(jsonParameter);
            String registRationId = jsonObject.optString("registRationId", null);
            if(registRationId==null) {
                if(requestURI.equals("targetVerify")){
                    LaUser laUserPara = GsonUtils.fromJson(jsonParameter, LaUser.class);
                    laUser = serverMapper.selectLaUserByUserName(laUserPara.getUserName());
                    if(laUser!=null){
                        laUserPara.setLaRegistRationId(laUser.getLaRegistRationId());
                        laUserPara.setRealUrl(laUser.getRealUrl());
                        laUserPara.setRegistRationId(laUser.getRegistRationId());
                        jsonParameter = GsonUtils.toJsonWtihNullField(laUserPara);
                    }
                }
            }
            else{
                laUser = serverMapper.selectLaUserByID(registRationId);
            }
            if(laUser==null){
                return GsonUtils.toJsonWtihNullField(new CommonResponseDTO("02", "账号不存在"));
            }
        }
//        if(requestURI.equals("targetVerify")){
//            LaUser laUserPara = GsonUtils.fromJson(jsonParameter, LaUser.class);
//            return GsonUtils.toJsonWtihNullField(loadPlatformService.targetVerify(laUserPara));
//        }

        String token = headers.get("token");
        try {
            String decryptBody = loadPlatformService.getBodyFromLoadPlatform(requestURI, laUser, jsonParameter, token);
            return decryptBody;
        }catch (Exception e){
            return e.getMessage();
        }
    }

    //{ "userName":"account001", "password":"123456", "demandName":"电力需求响应系统名称", "url":"127.0.0.1:443", "registRationId":"registRationId001" }
    @PostMapping(value = "/targetVerify")
    @ApiOperation(value = "电力需求响应系统认证验证", notes = "用于电力需求响应系统认证验证")
    public String targetVerify(@RequestBody String jsonParameter) {
        log.info("电力需求响应系统认证验证参数{}", jsonParameter);
        TargerVerifyDto targerVerifyDto = new TargerVerifyDto();
        TargerVerifyRequest targerVerifyRequest = GsonUtils.fromJson(jsonParameter, TargerVerifyRequest.class);
        log.info(targerVerifyRequest.toString());
        targerVerifyDto.setStatus("01");
        String token = SM3.encrypt(targerVerifyRequest.getUserName()+targerVerifyRequest.getPassword()+System.currentTimeMillis());
        targerVerifyDto.setToken(token);
        String registRationId = SM3.encrypt(targerVerifyRequest.getUserName());
        targerVerifyDto.setRegistRationId(registRationId);
        return GsonUtils.toJsonWtihNullField(targerVerifyDto);
    }

//    //{"registRationId":"registRationId001"}
//    @PostMapping(value = "/responseCons")
//    @ApiOperation(value = "负荷聚合平台获取可响应用户信息", notes = "用于负荷聚合平台获取可响应用户信息")
//    public String responseCons(@RequestHeader Map<String,String> headers, @RequestBody String jsonParameter) {
//        String token = headers.get("token");
//        log.info("负荷聚合平台获取可响应用户信息token：{}，参数{}", token, jsonParameter);
//        ResponseConsDto responseConsDto = new ResponseConsDto();
//        ResponseConsRequest responseConsRequest = GsonUtils.fromJson(jsonParameter, ResponseConsRequest.class);
//        if(responseConsRequest==null){
//            log.error("参数异常");
//            responseConsDto.setStatus("02");
//        }
//        else{
//            log.info(responseConsRequest.toString());
//            responseConsDto.setStatus("01");
//            List<ResponseConsListDataDto> responseUsers = new ArrayList<>();
//            ResponseConsListDataDto responseConsListDataDto_1 = new ResponseConsListDataDto();
//            responseConsListDataDto_1.setConsNo("consNo001");
//            responseUsers.add(responseConsListDataDto_1);
//            ResponseConsListDataDto responseConsListDataDto_2 = new ResponseConsListDataDto();
//            responseConsListDataDto_2.setConsNo("consNo002");
//            responseUsers.add(responseConsListDataDto_2);
//            responseConsDto.setResponseUsers(responseUsers);
//        }
//        return GsonUtils.toJsonWtihNullField(responseConsDto);
//    }

    //{"registRationId":"registRationId001", "eventId":"eventId001", "reponseType":"01", "activeTarget":"11.22", "isTest":"0", "activeStartTime1":"2022-01-22 17:33:21","activeEndTime1":"2022-01-22 17:33:21","activeStartTime2":"2022-01-22 17:33:21","activeEndTime2":"2022-01-22 17:33:21", "respLimitTime":"2022-01-22 17:33:21", "activeRange":"01", data:[{"rangeNo":"13402"}, {"rangeNo":"13403"}] }
    @PostMapping(value = "/targetResponse")
    @ApiOperation(value = "电力需求响应系统发布需求响应事件", notes = "用于电力需求响应系统发布需求响应事件")
    public String targetResponse(@RequestHeader Map<String,String> headers, @RequestBody String jsonParameter) {
        String token = headers.get("token");
        log.info("电力需求响应系统发布需求响应事件token：{}，参数{}", token, jsonParameter);
        TargerResponseDto targerResponseDto = new TargerResponseDto();
        TargerResponseRequest targerResponseRequest = GsonUtils.fromJson(jsonParameter, TargerResponseRequest.class);
        log.info(targerResponseRequest.toString());
        targerResponseDto.setStatus("01");
        targerResponseDto.setEventId(targerResponseRequest.getEventId());
        return GsonUtils.toJsonWtihNullField(targerResponseDto);
    }

    //{"registRationId":"registRationId001", "eventId":"eventId001", "processStatus":2 }
    @PostMapping(value = "/cancellEvent")
    @ApiOperation(value = "电力需求响应系统中止事件响应", notes = "用于电力需求响应系统中止事件响应")
    public String cancellEvent(@RequestHeader Map<String,String> headers, @RequestBody String jsonParameter) {
        String token = headers.get("token");
        log.info("电力需求响应系统中止事件响应token：{}，参数{}", token, jsonParameter);
        CancellEventDto cancellEventDto = new CancellEventDto();
        CancellEventRequest cancellEventRequest = GsonUtils.fromJson(jsonParameter, CancellEventRequest.class);
        if(cancellEventRequest==null){
            log.error("参数异常");
            cancellEventDto.setStatus("02");
        }
        else{
            log.info(cancellEventRequest.toString());
            cancellEventDto.setStatus("01");
            cancellEventDto.setEventId(cancellEventRequest.getEventId());
        }
        return GsonUtils.toJsonWtihNullField(cancellEventDto);
    }

}
